package com.example.demo.config;

import com.example.demo.common.AjaxResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Author :蕉绿
 * @Date : 2023/3/10 20:59
 * @Version : V1.0
 * @Description :
 */
//实现同一数据返回的保底类  在返回数据之前 检查数据的类型 是否需要封装成统一的数据
@ControllerAdvice

public class ResponseAdvice implements ResponseBodyAdvice {

    //jackson
    @Autowired
    private ObjectMapper objectMapper;

    //开关 true才会调用
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }


    //对数据格式进行校验和封装
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if((body instanceof AjaxResult)) {
            return body;
        }
        if(body instanceof String) {

            return objectMapper.writeValueAsString(AjaxResult.success(body));
        }
        return AjaxResult.success(body);
    }
}
